"""商品路由模块"""
from flask import Blueprint, request, jsonify
from app.utils.decorators import login_required
from app.models.product import Product
from app.models.barcode import generate_check_digit

bp = Blueprint('products', __name__, url_prefix='/api')

@bp.route('/products', methods=['GET'])
@login_required
def get_products():
    """获取商品列表（已废弃，使用按条码查询）"""
    return jsonify({'success': True, 'message': '请使用条码查询具体商品信息'}), 200

@bp.route('/products/<barcode>', methods=['GET'])
@login_required
def get_product(barcode):
    """根据条码获取商品"""
    try:
        product = Product.get_by_barcode(barcode)
        if product:
            return jsonify(product)
        else:
            return jsonify({'success': False, 'message': '商品不存在'}), 404
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/products', methods=['POST'])
@login_required
def add_product():
    """添加商品"""
    try:
        product_data = request.json
        barcode = product_data.get('barcode')
        name = product_data.get('name')
        price = product_data.get('price')
        unit = product_data.get('unit')
        stock = product_data.get('stock')
        expiry_date = product_data.get('expiry_date')
        
        # 检查商品是否已存在
        existing = Product.get_by_barcode(barcode)
        if existing:
            return jsonify({'success': False, 'message': '商品已存在'}), 400
        
        Product.create(barcode, name, price, unit, stock, expiry_date)
        return jsonify({'success': True, 'message': '商品添加成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/products/<barcode>', methods=['PUT'])
@login_required
def update_product(barcode):
    """更新商品"""
    try:
        product_data = request.json
        
        # 检查商品是否存在
        existing = Product.get_by_barcode(barcode)
        if not existing:
            return jsonify({'success': False, 'message': '商品不存在'}), 404
        
        update_data = {}
        if 'name' in product_data:
            update_data['name'] = product_data['name']
        if 'price' in product_data:
            update_data['price'] = product_data['price']
        if 'unit' in product_data:
            update_data['unit'] = product_data['unit']
        if 'stock' in product_data:
            update_data['stock'] = product_data['stock']
        if 'expiry_date' in product_data:
            update_data['expiry_date'] = product_data['expiry_date']
        
        Product.update(barcode, **update_data)
        return jsonify({'success': True, 'message': '商品更新成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/products/<barcode>', methods=['DELETE'])
@login_required
def delete_product(barcode):
    """删除商品"""
    try:
        success = Product.delete(barcode)
        if success:
            return jsonify({'success': True, 'message': '商品删除成功'})
        else:
            return jsonify({'success': False, 'message': '商品不存在'}), 404
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/stock/warning', methods=['GET'])
# 移除登录限制以方便测试
def get_stock_warnings():
    """获取库存警告（支持分页）"""
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        
        # 调用模型方法获取分页数据
        result = Product.get_stock_warnings(page=page, page_size=page_size)
        return jsonify({
            'success': True,
            'products': result['products'],
            'total': result['total'],
            'page': result['page'],
            'page_size': result['page_size'],
            'total_pages': result['total_pages']
        })
    except Exception as e:
        # 添加更详细的错误信息
        import traceback
        error_info = {
            'message': f'数据库操作失败: {str(e)}',
            'error_type': str(type(e).__name__),
            'traceback': traceback.format_exc()
        }
        print(f"Error in get_stock_warnings: {error_info}")
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}', 'error_details': str(type(e).__name__)}), 500

@bp.route('/expiry/warning', methods=['GET'])
def get_expiry_warnings():  # 移除登录限制以方便测试
    """获取近效期警告（支持分页）"""
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        
        # 调用模型方法获取分页数据
        result = Product.get_expiry_warnings(page=page, page_size=page_size)
        return jsonify({
            'success': True,
            'products': result['products'],
            'total': result['total'],
            'page': result['page'],
            'page_size': result['page_size'],
            'total_pages': result['total_pages']
        })
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

